﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Cloak.Mvp;

namespace Cloak.Web.Mvp
{
	/// <summary>
	/// Base class for pages which serve as views in an MVP context
	/// </summary>
	public abstract class ViewPage : Page
	{
		#region Overrides : Control
		/// <summary>
		/// Handles the Load event of this control
		/// </summary>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			Present(this, new PresentableEventArgs());
		}

		/// <summary>
		/// Handles the OnLoadComplete event of this control
		/// </summary>
		protected override void OnLoadComplete(EventArgs e)
		{
			base.OnLoadComplete(e);

			if(!IsPostBack)
			{
				DataBind();
			}
		}

		/// <summary>
		/// Handles bubble events received by this control
		/// </summary>
		protected override bool OnBubbleEvent(object source, EventArgs args)
		{
			var cancel = false;
			var presentableArgs = args as PresentableEventArgs;

			if(presentableArgs != null)
			{
				cancel = true;

				Present(source, presentableArgs);
			}
			else
			{
				cancel = base.OnBubbleEvent(source, args);
			}

			return cancel;
		}
		#endregion

		/// <summary>
		/// Gets or sets the context in which this page is presented
		/// </summary>
		public IMvpContext MvpContext { get; set; }

		private void Present(object view, PresentableEventArgs args)
		{
			if(MvpContext != null && view != null)
			{
				MvpContext.Present(view, args.Presentation);
			}
		}
	}
}